package org.jugile.util;

import java.lang.reflect.Method;
import java.util.Map;

import org.jugile.util.Jugile;

/**
 * Simple S-expression query.
 * @author RAHKOJUK
 *
 */
public class Query extends Jugile {
	
	private Expr expr;

	public Query() {
	}

	public Query and(String fld, String value) { return and(expr("like",fld,value)); }
	public Query or(String fld, String value) { return or(expr("like",fld,value)); }
	public Query and(String op, String fld, Object value) { return and(expr(op,fld,value)); }
	public Query or(String op, String fld, Object value) { return or(expr(op,fld,value)); }
	
	public Query op(String op, String fld, String value) {
		expr = expr(op, fld, value);
		return this;
	}
	
	public Query filter(String op, Method filterMethod, Object[] filterParams) {
		Expr exp = new Expr(op,filterMethod,filterParams);
		return and(exp);
	}
	
	public Query match(String fld, String value) { return op("like",fld,value); }	
	public Query and(Expr e) { return op("and",e); }
	public Query or(Expr e) { return op("or",e); }

	private Query op(String op, Expr e) {
		if (expr == null) expr = e;
		else expr = new Expr(op,expr,e);
		return this;
	}
	
	private Expr expr(String op, String fld, Object value) {
		return new Expr(op, new Expr(fld), new Expr(value));
	}
	
	public boolean eval(Object o) {
		if (expr == null) return false;
		try { return expr.eval(o); } 
		catch (Exception e) { fail(e); return false; }
	}
	
	public String toString() {
		String res = "";
		if (expr != null) res += expr.toString();
		return res;
	}

	public String toSolr() {
		if (expr != null) return expr.toSolr();
		return "";
	}

	public String toSql() {
		if (expr != null) {
			String res = expr.toSql();
			if (res.startsWith(" AND ")) res = res.substring(5);
			return res;
		}
		return "";
	}
	
}
